package com.shopping.controller;

import com.shopping.entity.User;
import com.shopping.service.GoodsService;
import com.shopping.service.UserService;
import com.shopping.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.time.ZoneOffset;
import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private UserService userService;

    @Autowired
    private GoodsService goodsService;

    @RequestMapping("/to_list")
    public String toList(Model model,User user){
        model.addAttribute("user",user);

        //查询商品列表
        List<GoodsVO> goodsVOList = goodsService.listGoodsVO();
        model.addAttribute("goodsList",goodsVOList);
        return "goods_list";
    }

    @RequestMapping("/to_details/{goodsId}")
    public String toDetails(@PathVariable("goodsId")long id, Model model, User user){
        model.addAttribute("user",user);

        GoodsVO goodsVO = goodsService.getGoodsVOByGoodsId(id);
        model.addAttribute("goods",goodsVO);

        long startDate = goodsVO.getStartDate().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long endDate = goodsVO.getEndDate().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long now = System.currentTimeMillis();

        int miaoshaStatus=0;
        int remainSeconds=0;

        if(startDate<now){//秒杀未开始倒计时
            miaoshaStatus=0;
            remainSeconds= (int) ((now-startDate)/1000);
        }else if(now>endDate){//秒杀以结束
            miaoshaStatus=2;
            remainSeconds=-1;

        }else{//秒杀进行中
            miaoshaStatus=1;
            remainSeconds=0;
        }

        model.addAttribute("miaoshaStatus",miaoshaStatus);
        model.addAttribute("remainSeconds",remainSeconds);
        return "goods_details";
    }
}
